﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZK.Common
{
    /// <summary>
    /// 读取AppConfig
    /// </summary>
    public class AppConfigHelper
    {
        public static string userName = "";
        //获取Configuration对象
        static Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        /// <summary>
        /// 根据Key读取元素的Value
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetAppSettings(string key)
        {
            //根据Key读取元素的Value
            string name = config.AppSettings.Settings[key].Value;
            return name;
        }
        /// <summary>
        /// 写入元素的Value(更新)
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void SetAppSettings(string key, string value)
        {
            //写入元素的Value
            config.AppSettings.Settings[key].Value = value;
            FinalAppSettings();
        }
        /// <summary>
        /// 增加元素
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public static void AddAppSettings(string key, string value)
        {
            //增加元素
            config.AppSettings.Settings.Add(key, value);
            FinalAppSettings();
        }
        /// <summary>
        /// 删除元素
        /// </summary>
        /// <param name="key"></param>
        public static void DelAppSettings(string key)
        {
            //删除元素
            config.AppSettings.Settings.Remove(key);
            FinalAppSettings();
        }
        /// <summary>
        /// 刷新
        /// </summary>
         private static void FinalAppSettings()
        {
            //一定要记得保存，写不带参数的config.Save()也可以
            config.Save(ConfigurationSaveMode.Modified);
            //刷新，否则程序读取的还是之前的值（可能已装入内存）
           ConfigurationManager.RefreshSection("appSettings");
        }
    }
}
